package com.sparrow.common.thread.runnable;

import com.sparrow.common.metric.MetricsManager;
import com.sparrow.common.thread.IdExecutorGroup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 带名字的任务 会进行性能统计
 */
public class NamedRunnable implements Runnable {

    private static Logger logger = LoggerFactory.getLogger(IdExecutorGroup.class);

    private String name;

    private Runnable runnable;

    public NamedRunnable(String name, Runnable runnable) {
        this.name = name;
        this.runnable = runnable;
    }

    @Override
    public void run() {
        try {
            MetricsManager.timer(name).record(() -> {
                runnable.run();
            });
        } catch (Throwable t) {
            logger.error("task:{} run error!", name, t);
        }
    }
}
